<template>
  <div class="excalidraw-wrapper">
    <div ref="excalidrawContainer" class="excalidraw-container"></div>
  </div>
</template>

<script>
export default {
  name: 'ExcalidrawWrapper',
  props: {
    // 初始化数据
    initialData: {
      type: String,
      default: null
    },
    // 是否为暗黑模式
    darkMode: {
      type: Boolean,
      default: true
    },
    // 是否只读模式
    viewMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      excalidrawModule: null,
      excalidrawAPI: null,
      isLoaded: false
    }
  },
  mounted() {
    this.loadExcalidraw()
  },
  beforeDestroy() {
    // 清除定时器
    if (this.changeInterval) {
      clearInterval(this.changeInterval)
    }
  },
  methods: {
    /**
     * 动态加载Excalidraw脚本
     */
    loadExcalidraw() {
      // 检查是否已经加载
      if (document.getElementById('excalidraw-script')) {
        this.initExcalidraw()
        return
      }

      // 创建脚本标签
      const script = document.createElement('script')
      script.id = 'excalidraw-script'
      script.src = 'https://unpkg.com/@excalidraw/excalidraw@0.18.0/dist/excalidraw.production.min.js'
      script.crossOrigin = 'anonymous'
      script.onload = () => {
        this.initExcalidraw()
      }
      script.onerror = (error) => {
        console.error('Failed to load Excalidraw:', error)
        this.$emit('load-error', error)
      }

      // 添加到文档
      document.head.appendChild(script)

      // 添加CSS
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = 'https://unpkg.com/@excalidraw/excalidraw@0.18.0/dist/excalidraw.min.css'
      document.head.appendChild(link)
    },

    /**
     * 初始化Excalidraw
     */
    initExcalidraw() {
      if (!window.ExcalidrawLib) {
        console.error('Excalidraw library not loaded')
        return
      }

      const container = this.$refs.excalidrawContainer
      const { createRoot, exportToBlob, exportToSvg } = window.ExcalidrawLib

      // 保存引用
      this.excalidrawModule = {
        createRoot,
        exportToBlob,
        exportToSvg
      }

      // 初始化数据
      let initialData = null
      if (this.initialData) {
        try {
          initialData = JSON.parse(this.initialData)
        } catch (e) {
          console.error('Failed to parse initialData:', e)
        }
      }

      // 创建Excalidraw实例
      const excalidrawRoot = createRoot(container)
      this.excalidrawAPI = excalidrawRoot.render({
        initialData,
        viewModeEnabled: this.viewMode,
        theme: this.darkMode ? 'dark' : 'light'
      })

      // 监听变化事件
      // 在新版本中，onChange 可能需要通过 props 传递
      if (this.excalidrawAPI && this.excalidrawAPI.updateScene) {
        // 定期检查场景变化
        this.changeInterval = setInterval(() => {
          const elements = this.getSceneData()
          const appState = this.excalidrawAPI.getAppState && this.excalidrawAPI.getAppState()
          if (elements) {
            this.$emit('change', { elements, appState })
          }
        }, 1000) // 每秒检查一次变化
      }

      this.isLoaded = true
      this.$emit('loaded', this.excalidrawAPI)
    },

    /**
     * 获取当前画板数据
     * @returns {Object} 画板数据
     */
    getSceneData() {
      if (!this.excalidrawAPI || !this.isLoaded) return null
      // 新版本 API 可能使用不同的方法获取场景元素
      if (this.excalidrawAPI.getSceneElements) {
        return this.excalidrawAPI.getSceneElements()
      } else if (this.excalidrawAPI.getElements) {
        return this.excalidrawAPI.getElements()
      } else if (this.excalidrawAPI.scene && this.excalidrawAPI.scene.getElements) {
        return this.excalidrawAPI.scene.getElements()
      }
      return null
    },

    /**
     * 导出为JSON
     * @returns {String} JSON字符串
     */
    exportToJSON() {
      if (!this.excalidrawAPI || !this.isLoaded) return null
      const elements = this.getSceneData()
      let appState = null
      
      // 适配不同版本的 API
      if (this.excalidrawAPI.getAppState) {
        appState = this.excalidrawAPI.getAppState()
      } else if (this.excalidrawAPI.getState) {
        appState = this.excalidrawAPI.getState()
      } else if (this.excalidrawAPI.scene && this.excalidrawAPI.scene.getAppState) {
        appState = this.excalidrawAPI.scene.getAppState()
      }
      
      return JSON.stringify({ elements, appState })
    },

    /**
     * 导出为图片
     * @returns {Promise<Blob>} 图片Blob
     */
    async exportToImage() {
      if (!this.excalidrawAPI || !this.isLoaded || !this.excalidrawModule.exportToBlob) return null
      const elements = this.getSceneData()
      if (!elements) return null
      
      try {
        const blob = await this.excalidrawModule.exportToBlob({
          elements,
          mimeType: 'image/png',
          appState: {
            theme: this.darkMode ? 'dark' : 'light',
            exportWithDarkMode: this.darkMode
          }
        })
        return blob
      } catch (error) {
        console.error('Failed to export image:', error)
        return null
      }
    },

    /**
     * 导出为SVG
     * @returns {Promise<SVGSVGElement>} SVG元素
     */
    async exportToSVG() {
      if (!this.excalidrawAPI || !this.isLoaded || !this.excalidrawModule.exportToSvg) return null
      const elements = this.getSceneData()
      if (!elements) return null
      
      try {
        const svg = await this.excalidrawModule.exportToSvg({
          elements,
          appState: {
            theme: this.darkMode ? 'dark' : 'light',
            exportWithDarkMode: this.darkMode
          }
        })
        return svg
      } catch (error) {
        console.error('Failed to export SVG:', error)
        return null
      }
    }
  }
}
</script>

<style scoped>
.excalidraw-wrapper {
  width: 100%;
  height: 400px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.excalidraw-container {
  width: 100%;
  height: 100%;
}
</style>